'use strict'

var mongoose = require('mongoose')
var Component = mongoose.model('Component')
var Category = mongoose.model('Categoryzujian')
var _ = require('underscore')
// detail
exports.detail = function *(next) {
  var id = this.request.body.id
  var component = yield Component.findOne({_id: id}).exec()
  this.body = {
    success: true,
    component:component
  }
  yield next
}

// admin post movie
exports.save = function *(next) {
  var componentObj = this.request.body || {}
  var _component

  if (componentObj._id) {
    console.log(666)
    var component = yield Component.findOne({_id: componentObj._id}).exec()
  
    _component = _.extend(component, componentObj)
    yield _component.save()
    this.body = {success:true,id: component._id}
  }
  else {
    _component = new Component(componentObj)

    var categoryId = componentObj.category
    var categoryName = componentObj.categoryName
    component = yield _component.save()

    if (categoryId) {
      var category = yield Category.findOne({_id:categoryId}).exec()
      category.components.push(component._id)

      yield category.save()
      this.body = {success:true,id: component._id}
    }
    else if (categoryName) {
      var category = new Category({
        name: categoryName,
        components: [component._id]
      })

      category = yield category.save()
      component.category = category._id
      yield component.save()
      this.body = {success:true,id: component._id}
    }
  }
}
// 删除
exports.del = function *(next) {
  var id = this.query.id
  if (id) {
    try{
      Component.remove({_id: id}).exec()
      this.body = {success: true}
    }
    catch(err){
      console.log(err)
      this.body = {success: false}
    }
    
  }
}
//页面
exports.page = function *(next){
  var components = yield Component.find({}).populate('category', 'name').exec()
  var categories = yield Category.find({}).exec()
  yield this.render('pages/draggleManage',{
    components: components,
    categories: categories
  })
}

exports.show = function *(){
  var categories = yield Category.find({})
    .populate({
      path: 'components'
    }).lean().exec()
  categories.forEach(function(item,index){
    item.components.forEach(function(subitem,index){
      subitem.btnoption = JSON.parse(subitem.btnoption)
    })
  })
  console.log(categories)
  yield this.render('pages/htmldrop',{
    categories: categories
  })
}